package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.MdmUserExport;
import com.kaili.basic.pojo.entity.MdmUserQueryEntity;
import com.kaili.basic.pojo.vo.MdmUserVO;
import com.kaili.basic.service.IBaseUserService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.aop.OperateLogAspect;
import com.kaili.common.aop.log.enums.FunctionName;
import com.kaili.common.aop.log.enums.OperateType;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.LoginDetailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户管理控制类
 * Created by linjian on 19-8-1.
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "基础用户管理", description = "基础用户管理相关API")
@RestController
public class MdmUserManagerController {

    @Autowired
    private IBaseUserService iBaseUserService;

    /**
     * 根据条件查询用户信息
     */
    @GetMapping("/userManager/query")
    @ApiOperation(value = "查询用户", notes = "根据条件查询用户列表")
    public Page<MdmUserQueryEntity> getBaseUsersByKeywords(@ModelAttribute MdmUserQueryDto baseUser) {
        return iBaseUserService.getBaseUsersByConditions(new Page<MdmUserQueryEntity>(baseUser.getPage(), baseUser.getPageSize()), baseUser);
    }

    /**
     * 根据id查询用户信息
     */
    @GetMapping("/userManager/query/{userId}")
    @ApiOperation(value = "根据id查询用户", notes = "根据id查询用户列表")
    public MdmUserQueryEntity getBaseUsersById(@ApiParam("userId") @PathVariable("userId")  Integer id){
        return iBaseUserService.getBaseUsersById(id);
    }

    /**
     * 新增用户
     */
    @ApiOperation(value = "新增用户", notes = "新增用户")
    @OperateLogAspect(functionName = FunctionName.baseUserManager,operateType = OperateType.ADD, key = "base.user.manager")
    @PostMapping("/userManager/addUser")
    public RestStatus addFacilityVersion(@RequestBody MdmUserAddDto dto){
        MdmUserVO mdmUserVO = new MdmUserVO();
        BeanUtils.copyProperties(dto, mdmUserVO);
        if (mdmUserVO.getUserName().length()<4 || mdmUserVO.getUserName().length()>20){
            return null;
        }
        //根据用户名查询用户是否已经存在
        MdmUserVO isExist = iBaseUserService.queryUserByUserName(mdmUserVO.getUserName());
        if (isExist != null){
            return CommonStatus.ADD_DEFEAT;
        }
        //姓名
        if (mdmUserVO.getName() == null || "".equals(mdmUserVO.getName()) || mdmUserVO.getName().length()>20){
            return CommonStatus.ADD_DEFEAT;
        }
        Long createBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        mdmUserVO.setCreatedBy(createBy);
        mdmUserVO.setCreatedTime(new Date());
        String email = mdmUserVO.getEmail();
        if (null != email && !"".equals(email)){
            if (!patternMail(mdmUserVO.getEmail())){
                return CommonStatus.EMAIL_DEFEAT;
            }
        }
        iBaseUserService.addNewUser(mdmUserVO);
        return CommonStatus.ADD_OK;
    }

    //判断邮箱格式是否正确
    public boolean patternMail(String str){
        //邮箱校验规则
        String check = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        Pattern pattern = Pattern.compile(check);
        Matcher martch = pattern.matcher(str);
        boolean isMatched = martch.matches();
        if (!isMatched){
            return false;
        }
        return true;
    }

    /**
     * 更新用户信息
     */
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
    @OperateLogAspect(functionName = FunctionName.baseUserManager,operateType = OperateType.UPDATE, key = "base.user.manager")
    @PutMapping("/userManager/update")
    public RestStatus updateUser(@RequestBody MdmUserUpdateDto dto){
        MdmUserVO mdmUserVO = new MdmUserVO();
        BeanUtils.copyProperties(dto, mdmUserVO);
        Long modifyBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        if (modifyBy == null){
            mdmUserVO.setModifyId(-1L);
        }
        mdmUserVO.setModifyId(modifyBy);
        mdmUserVO.setModifyTime(new Date());
        iBaseUserService.updateUser(mdmUserVO);
        return CommonStatus.UPDATE_OK;
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @DeleteMapping("/userManager/{userId}")
    @OperateLogAspect(functionName = FunctionName.baseUserManager,operateType = OperateType.DELETE, key = "base.user.manager")
    public RestStatus deleteUserById(@ApiParam("userId") @PathVariable("userId")  Integer id){
        iBaseUserService.deleteUserById(id);
        return CommonStatus.DELETE_OK;
    }

    /**
     * 操作启用
     */
    @ApiOperation(value = "启用", notes = "启用")
    @GetMapping("/userManager/enable/{userId}")
    @OperateLogAspect(functionName = FunctionName.baseUserManager,operateType = OperateType.UPDATE, key = "base.user.manager")
    public Integer modifyEnableById(@ApiParam("userId") @PathVariable("userId")  Integer id){
        int result = 1;
        iBaseUserService.updateRdStatusEnable(id);
        return result;
    }

    /**
     * 操作禁用
     */
    @ApiOperation(value = "禁用", notes = "禁用")
    @GetMapping("/userManager/disable/{userId}")
    @OperateLogAspect(functionName = FunctionName.baseUserManager,operateType = OperateType.UPDATE, key = "base.user.manager")
    public Integer modifyDisableById( @ApiParam("userId") @PathVariable("userId") Integer id){
        int result = 2;
        iBaseUserService.updateRdStatusDisable(id);
        return result;
    }


    /**
     * 导入用户数据
     */
    @PostMapping(value = "/userManager/import")
    //@ApiOperation("批量导入用户信息")
    public RestStatus importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<MdmUserImportDto> list = ExcelUtil.importExcel(file, 1, 2, MdmUserImportDto.class);
        MdmUserVO mdmUserVO = new MdmUserVO();
        for(MdmUserImportDto dto : list){
            BeanUtils.copyProperties(dto, mdmUserVO);
            if (null == mdmUserVO.getUserName() || null == mdmUserVO.getName() || null == mdmUserVO.getOrgId()){
                return CommonStatus.ADD_DEFEAT;
            }
            iBaseUserService.addNewUser(mdmUserVO);
        }
        return CommonStatus.OK;
    }

    /**
     * 导出用户
     */
    @GetMapping("/userManager/export")
    @ApiOperation(value = "导出用户信息")
    public void export(HttpServletResponse response, @ModelAttribute MdmUserQueryDto dto) throws RestException {
        List<MdmUserExport> list = iBaseUserService.usersInfoExport(dto);
        ExcelUtil.exportExcel(list,"用户信息","sheet1", MdmUserExport.class, UUID.randomUUID().toString()+".xls",response);
    }

    /**
     * 修改密码
     */
    @PutMapping("/userManager/modifyPWD")
    @ApiOperation(value = "用户修改密码")
    @OperateLogAspect(functionName = FunctionName.baseUserManager,operateType = OperateType.UPDATE, key = "base.user.manager")
    public RestStatus modifyPassword(@RequestBody MdmUserModifyPWDDto dto){

        MdmUserVO mdmUserVO = new MdmUserVO();
        BeanUtils.copyProperties(dto, mdmUserVO);
        Long modifyBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        if (modifyBy == null){
            modifyBy=-1L;
        }
        mdmUserVO.setUserId(dto.getUserId());
        mdmUserVO.setModifyId(modifyBy);
        mdmUserVO.setModifyTime(new Date());
        iBaseUserService.updateUser(mdmUserVO);
        return CommonStatus.UPDATE_OK;
    }

}
